<?php

namespace app\controller;

use app\model\SmsLog;
use support\Request;
use app\model\User;
use support\Log;

class AuthController extends BaseController
{

    protected $noNeedLogin = ['login'];

    public function login(Request $request)
    {
        $phone = $request->input('phone');
        $code = $request->input('code');

        // 验证手机号格式
        if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
            return $this->error('手机号格式不正确');
        }

        // 验证验证码
        // TODO: 实现验证码验证逻辑
        if (!$this->verifyCode($phone, $code)) {
            return $this->error('验证码错误或已过期');
        }

        // 查找或创建用户
        $user = User::findByPhone($phone);
        if (!$user) {
            $user = User::create([
                'username' => $phone,
                'phone' => $phone,
                'nickname' => '用户' . substr($phone, -4),
                'status' => 1
            ]);
        }

        // 生成token
        $token = $user->generateToken();

        return $this->success([
            'token' => $token,
            'user' => $user
        ], '登录成功');
    }

    private function verifyCode($phone, $code)
    {
        // TODO: 实现验证码验证逻辑
        // 这里需要根据你的验证码存储和验证方式来实现
        $check = SmsLog::query()
            ->where(
                [
                    'code' =>  $code,
                    'mobile' => $phone,
                    'send_status' => 1,
                    'is_verify' => 0,
                ]
            )->first();

        if(empty($check)){
            return false;
        }

        if(time() - $check['send_time'] > 300){
            return false;
        }

        $check->is_verify = 1;
        $check->save();

        return true;
    }

    /**
     * 微信授权登录
     * @param Request $request
     * @return \Webman\Http\Response
     */
    public function wechatLogin(Request $request)
    {
      
        $code = $request->post('code');
        if (!$code) {
            return $this->error('缺少code参数');
        }
        $config = config('wechat');
       
        $appid = $config['appid'];
        $secret = $config['secret'];
        // 1. 用code换取openid
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $resp = file_get_contents($url);
        $data = json_decode($resp, true);
        if (empty($data['openid'])) {
            return $this->error('微信登录失败: ' . ($data['errmsg'] ?? '未知错误'));
        }
        $openid = $data['openid'];
        // 2. 查找或创建用户
        $user = $this->getUser($request);
        $user['openid'] = $openid;
        $user->save();
        
        return $this->success([
            'user' => $user
        ], '登录成功');
    }
}
